import React, { Component } from 'react';
import { Modal } from 'antd';
import { config } from 'utils'
import newWebchannel from '../../../public/qwebchannel'
const { host } = config
export default class Eloam extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      videoType: 0,
      confirmLoading: false,
    };

    this.eloamGlobal = null;
    this.eloam = window.eloam;
    this.formData = null;
  }
  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextProps.key != this.props.key ||
      nextState.visible != this.state.visible ||
      nextState.confirmLoading != this.state.confirmLoading
    );
  }
  componentWillMount() {
    this.eloamGlobal = this.eloam.init(host + "/appCollectionFile/uploadPC");
  }
  componentDidMount() {
  //  document.getElementById("idText").onclick = function() {
  //    console.log('3333')
  //   //第四个参数如果为空则会设置指定的长宽；如果不为空则把视频大小改为正常大小
  //   // dialog.get_functionTypes("setScanSizeSub", "800", "1024", "");
  //   //dialog.get_functionTypes("setScanSizeSub", "800", "1024", "ori");
    
  // };
    // console.log(x.innerHTML,'innerHTMLss')
  }
  componentWillUnmount() { }
  readIDCard() {
    if (!this.eloamGlobal) {
      alert('设备初始化失败');
      return;
    }
    this.eloamGlobal.DeinitIdCard();

    if (this.eloamGlobal.InitIdCard()) {
      if (this.eloamGlobal.ReadIdCard()) {
        const image = this.eloamGlobal.GetIdCardImage(1);
        const cardImage = this.eloamGlobal.GetIdCardImage(2);
        const base64 = image.GetBase64(13, 0x0080);
        const cardBase64 = cardImage.GetBase64(13, 0x0010);
        image.Destroy();

        const validEnd =
          this.eloamGlobal.GetIdCardData(13) +
          '/' +
          this.eloamGlobal.GetIdCardData(14) +
          '/' +
          this.eloamGlobal.GetIdCardData(15);
        const validStart =
          this.eloamGlobal.GetIdCardData(10) +
          '/' +
          this.eloamGlobal.GetIdCardData(11) +
          '/' +
          this.eloamGlobal.GetIdCardData(12);
        const idcard = {
          name: this.eloamGlobal.GetIdCardData(1),
          sex: this.eloamGlobal.GetIdCardData(2),
          nativePlace: this.eloamGlobal.GetIdCardData(3),
          dateOfBirth:
            this.eloamGlobal.GetIdCardData(4) +
            '/' +
            this.eloamGlobal.GetIdCardData(5) +
            '/' +
            this.eloamGlobal.GetIdCardData(6),
          address: this.eloamGlobal.GetIdCardData(7),
          cardID: this.eloamGlobal.GetIdCardData(8),
          authority: this.eloamGlobal.GetIdCardData(9),
          validStart,
          validEnd,
          base64,
          cardBase64
        };
        return idcard;
      } else {
        alert('读取身份证失败,请放置身份证！');
      }

      this.eloamGlobal.DeinitIdCard();
    } else {
      alert('初始化身份证阅读器失败！');
    }
  }
  readBarcode() {
    const ret = this.eloamGlobal.InitBarcode()
    if (!ret) {
      alert("条码/二维码识别器初始化失败!")
      return
    }
    const videoView = document.getElementById('video-view');
    const image = window.videoMain.CreateImage(0, videoView.GetView());
    if (!this.eloamGlobal.DiscernBarcode(image)) {
      alert("条码/二维码识别失败!")
      return
    }
    const sum = this.eloamGlobal.GetBarcodeCount()
    if (sum > 1) {

    }
    const data = this.eloamGlobal.GetBarcodeData(0)
    const str = data.split("\n")
    const org = {}
    const keyMap = {
      "统一社会信用代码": "creditCode",
      "企业注册号": "tdup",
      "名称": "name",
      "登记机关": "authority",
      "登记日期": "recordDate",
    }
    str.map((item) => {
      if (!item.trim()) {
        return
      }

      const itemArray = item.split("：")
      if (!keyMap[itemArray[0]]) {
        return
      }
      org[keyMap[itemArray[0]]] = itemArray[1].trim()
    })
    this.props.onBarcodeDecode && this.props.onBarcodeDecode(org)
    this.setState({
      visible: false
    });
  }
  readFinger() {
    if (!this.eloamGlobal) {
      alert("插件初始化失败!")
      this.fingerReadDone("")
      return
    }
    const r1 = this.eloamGlobal.InitBiokey()
    if (!r1) {
      alert("指纹设备初始化失败!")
      this.fingerReadDone("")
      return
    }

    setTimeout(() => {
      const r2 = this.eloamGlobal.GetBiokeyFeature()
      if (!r2) {
        alert("获取指纹特征失败!")
        this.fingerReadDone("")
        return
      }
    }, 1000)
    //异步获取指纹数据
    let imageBase64 = ""
    setTimeout(() => {
      imageBase64 = sessionStorage.getItem("fingerImage")
      //清空指纹数据,防止下次再读取到
      if (imageBase64) {
        sessionStorage.setItem("fingerImage", "")
      }
      this.fingerReadDone(imageBase64)
    }, 5000)

  }
  fingerReadDone(data) {
    this.eloamGlobal.StopGetBiokeyFeature()
    this.eloamGlobal.DeinitBiokey();
    this.props.onBiokey && this.props.onBiokey(data);
  }
  closeVideoModal() {
    this.setState({
      visible: false
    });
  }
  closeVideoMain() {
    const videoMain = this.eloam.videoMain || window.videoMain;
    if (videoMain) {
      videoMain.Destroy();
      this.eloam.videoMain = null;
      const videoView = document.getElementById('video-view');
      videoView.SetText('', 0);
    }
  }
  closeVideoAssist() {
    const videoAssist = this.eloam.videoAssist || window.videoAssist;
    if (videoAssist) {
      videoAssist.Destroy();
      this.eloam.videoAssist = null;
      const videoView = document.getElementById('video-view');
      videoView.SetText('', 0);
    }
  }

  openVideoMain(type, data) {
    this.setState({
      visible: true,
      videoType: type ? type : 0,
    });

    this.formData = data

    setTimeout(() => {
      this.closeVideoMain();
      const deviceMain = this.eloam.deviceMain;

      if (deviceMain) {
        const videoMain = deviceMain.CreateVideo(2, 2); //1920*1080
        if (videoMain) {
          window.videoMain = videoMain;
          const videoView = document.getElementById('video-view');
          videoView.SelectVideo(videoMain);
          videoView.SetText('打开视频中，请等待...', 0);
        }
      }
    }, 1000);
  }
  openVideoAssist() {
    this.setState({
      visible: true,
      videoType: 1,
    });
    setTimeout(() => {
      this.closeVideoAssist();
      const deviceAssist = this.eloam.deviceAssist;

      if (deviceAssist) {
        const videoAssist = deviceAssist.CreateVideo(2, 2); //1920*1080
        if (videoAssist) {
          window.videoAssist = videoAssist;
          const videoView = document.getElementById('video-view');
          videoView.SelectVideo(videoAssist);
          videoView.SetText('打开视频中，请等待...', 0);
        }
      }
    }, 1000);
  }
  takePictureAndUpload({
    userId,//创建者id
    localId, //自然人，机构或批次的id
    partyNumber,//批次中事项的id
    type, // 0:自然人，1:机构，2:批次
    dataType,  //自然人（0:婚姻状况证明资料，1:户口信息资料，2:身份证头像，3:签名，4:指纹，5:身份证正面，6:身份证反面，7:资产信息） 
    //机构（0:法人信息资料，1:资产信息资料，2:其它信息，3: 营业执照 ） 
    //批次（0:公证事项信息 1:当事人补充信息 2:收据信息）
  }) {
    const videoView = document.getElementById('video-view');
    // const image = window.videoAssist.CreateImage(0, videoView.GetView());
    const image = window.videoMain.CreateImage(0, videoView.GetView());
    // const base64 = image.GetBase64(2, 0x0200);
    // image.Destroy();
    // const img = 'data:image/jpeg;base64,' + base64;
    // console.log(img,'img21212')
    // console.log('232222img')
    // const image = window.videoAssist.CreateImage(0, videoView.GetView());
    // console.log(image1,'image1')
    const md5 = image.GetMD5(2, 0)
    //md5#userId#localId#partyNumber#type#dataType.jpg
    const fileName = md5 + "#" + userId + "#" + localId + "#" + partyNumber + "#" + type + "#" + dataType + ".jpg"
    //  console.log(fileName,'fileName')
    // console.log(fileName,'fileName')
    const infoser = this.eloam.upload(image, fileName);
    // console.log(infoser,'infoser')
    this.props.onTakePicture && this.props.onTakePicture(infoser);

  }
  takePictureBase64() {
    const videoView = document.getElementById('video-view');
    const image = window.videoMain.CreateImage(0, videoView.GetView());
    const base64 = image.GetBase64(2, 0x0200);
    image.Destroy();
    const img = 'data:image/jpeg;base64,' + base64;
    this.props.onTakePictureBase64 && this.props.onTakePictureBase64(img);
    this.closeVideoMain()
    this.setState({
      visible: false
    });
  }
  takeAssistPicture() {
    const videoView = document.getElementById('video-view');
    const image = window.videoAssist.CreateImage(0, videoView.GetView());
    // console.log('1111image')
    const base64 = image.GetBase64(2, 0x0200);
    image.Destroy();
    const img = 'data:image/jpeg;base64,' + base64;
    // console.log(img,'img')
    // console.log('232222img')
    this.props.onAssistPicture && this.props.onAssistPicture(img);
    this.closeVideoAssist()
    this.setState({
      visible: false
    });
  }

  handleOk() {
    const { videoType, confirmLoading } = this.state;
    if (confirmLoading) {
      return
    }
    if (videoType === 0) {
      if (!this.formData) {
        this.takePictureBase64();
        return
      }
      //主摄像头,拍照使用
      this.takePictureAndUpload(this.formData);
    } else if (videoType === 1) {
      //副摄像头,认证对比
      this.takeAssistPicture();

    } else {
      //二维码识别
      this.readBarcode()
    }
  }
  handleCancel() {
    this.setState({
      visible: false,
    });
    this.closeVideoMain();
    this.closeVideoAssist();

  }
  render() {
    const { videoType, visible, confirmLoading } = this.state;
    let okText = '拍照';
    if (videoType == 1) {
      okText = '拍照对比';
    } else if (videoType == 2) {
      okText = '二维码识别';
    }
    return (
      <Modal
        title={okText}
        width={650}
        mask={false}
        maskClosable={false}
        confirmLoading={confirmLoading}
        visible={visible}
        onOk={() => this.handleOk()}
        onCancel={() => this.handleCancel()}
        destroyOnClose={true}
        cancelText="取消"
        okText={okText}
      > 
      {/* <object
          style={{ backgroundColor: '#070707' }}
          id="closeHtml"
          border="0"
          classID="CLSID:26BA9E7F-78E9-4FB8-A05C-23232"
          width="200"
          height="100"
        /> */}
        <object
          style={{ backgroundColor: '#fff' }}
          id="video-view"
          border="0"
          classID="CLSID:26BA9E7F-78E9-4FB8-A05C-A4185D80D759"
          width="600"
          height="300"
        />
      </Modal>
    );
  }
}
